<?php

namespace app\admin\controller;


use app\service\TemplateService;
use app\admin\validate\TemplateValidate;
use think\exception\ValidateException;

class Template extends Admin
{
    public function __construct(TemplateService $service)
    {
        parent::__construct();
        $this->service = $service;
    }

    public function index()
    {
        if (!$this->request->isPost()) {
            $this->assign("title", "模板通知列表");
            return $this->fetch("index");
        }
        $params = $this->request->post();
        $where = [];
        if (!empty($params["name"])) {
            $where[] = ['name', 'like', "%{$params['name']}%"];
        }
        if (!empty($params["status"])) {
            $where[] = ["status", "=", $params["status"]];
        }
        $ret = $this->service->getList($where);
        $this->result($ret);
    }

    private function save()
    {
        $action = $this->request->action();
        $params = $this->request->post();
        $data = [
            "name" => $params["name"],
            "id" => isset($params["id"]) ? $params["id"] : 0,
            "sort" => $params["sort"],
            "mark" => $params["mark"],
            "title" => $params["title"],
            "sms_content" => $params["sms_content"],
            "email_content" =>$params["email_content"]
        ];
        try {
            validate(TemplateValidate::class)->scene($action)->check($data);
        } catch (ValidateException $e) {
            $this->error($e->getError());
        }
        $ret = $this->service->save($data);
        if ($ret) {
            $this->success("操作成功");
        } else {
            $this->error("保存失败");
        }
    }

    public function add()
    {
        if (!$this->request->isPost()) {
            $this->assign("vo", null);
            $this->assign("title","添加模板");
            return $this->fetch("form");
        }
        return $this->save();
    }

    public function edit()
    {
        if (!$this->request->isPost()) {
            $id = $this->request->get("id");
            if (!$id) {
                throw new ValidateException("缺少id");
            }
            $vo = $this->service->get($id);
            $this->assign("title","编辑模板");
            $this->assign("vo", $vo);
            return $this->fetch("form");
        }
        return $this->save();
    }


    public function status()
    {
        $params = $this->request->Post();
        try {
            validate(TemplateValidate::class)->scene("status")->check($params);
        } catch (ValidateException $e) {
            $this->error($e->getError());
        }
        $this->service->setStatus($params["id"], $params["status"]);
        $this->success("操作成功");
    }
}